package controller

import (
	"log"
	"sort"
	"strings"

	"user-agent/database/bean"
	"user-agent/database/myredis"

	"github.com/kataras/iris/context"
)

type AliveMachine struct {
	Time    int64  `json:"time"`
	Count   int    `json:"count"`
	ID      string `json:"id"`
}

type aliveCtrl struct {
	Model      *bean.AliveBean
	staticBean *bean.StatisticsBean
}

var Alive = &aliveCtrl{
	Model:      &bean.AliveBean{},
	staticBean: &bean.StatisticsBean{},
}

func get() (list []AliveMachine, err error) {
	if err = myredis.Sort(&list, "vps", "vps:*->time", "vps:*->time", "vps:*->count", "vps:*->id"); err != nil {
		return
	}
	sort.Slice(list, func(i, j int) bool {
		switch strings.Compare(list[i].ID, list[j].ID) {
		case -1:
			return true
		case 1:
			return false
		}
		return true
	})
	return
}

func (ctrl *aliveCtrl) Get(ctx context.Context) {
	list, err := get()
	if err != nil {
		log.Println(err)
		ctx.StatusCode(500)
	}
	if list != nil {
		ctx.JSON(list)
	} else {
		ctx.WriteString("[]")
	}
}

func (ctrl *aliveCtrl) GetOne(ctx context.Context) {
	id := ctx.URLParam("id")
	id = strings.Trim(id, " ")
	if id == "" {
		ctx.StatusCode(403)
		return
	}
	list, err := ctrl.Model.GetRecordStatistics(id)
	if err != nil {
		log.Println(err)
		ctx.StatusCode(500)
		return
	}
	ctx.JSON(list)
}

func (ctrl *aliveCtrl) GetOneRecords(ctx context.Context) {
	id := ctx.URLParam("id")
	id = strings.Trim(id, " ")
	if id == "" {
		ctx.StatusCode(403)
		return
	}
	list, err := ctrl.Model.GetOneAllActivity(id, 200)
	if err != nil {
		log.Println(err)
		ctx.StatusCode(500)
		return
	}
	ctx.JSON(list)
}

func (ctrl *aliveCtrl) GetOneStatistic(ctx context.Context) {
	mac := ctx.Params().Get("mac")
	start := ctx.URLParamInt64Default("start", 0)
	end := ctx.URLParamInt64Default("end", 0)
	if list, err := ctrl.staticBean.GetList(mac, start, end); err != nil {
		log.Println(err)
		ctx.StatusCode(500)
	} else {
		ctx.JSON(list)
	}
}

func (ctrl *aliveCtrl) DelOne(ctx context.Context) {
	id := ctx.URLParam("id")
	id = strings.Trim(id, " ")
	if id == "" {
		ctx.StatusCode(403)
		return
	}
	myredis.Del("vps:" + id)
	myredis.SRem("vps", id)
	ctx.StatusCode(200)
}
